package com.homwee.factory;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import com.homwee.tvap.common.srvfunc.FactorySetting;
import android.app.Activity;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.homwee.factory.util.BarCodeUtils;
import android.graphics.Color;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.content.Intent;

public class BarCodeShowActivity extends Activity  {
	EditText mEditText =null; 
	TextView barCodeTextViewValue;
	TextView barCodeTextViewPresentationText;
	TextView barCodeTextViewPid ;
	String  factoryBarCodeStr ="";
	private RelativeLayout mRootLayout,mainLayout;
	public static Context mContext=null;
	FactorySetting factory =null;
        private BroadcastReceiver stopBroadcastReceiver = null;
	
	public static long startTime =0L;
	 private final  ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
	 private ScheduledFuture future=null ;
	//= System.currentTimeMillis();
	//Log.v("tv1","runtime:"+(endTime-startTime));
	
	private Handler mHandler =new Handler();
	private Runnable mRunnable =new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			Log.v("tv","set BarCode String length="+factoryBarCodeStr.length());
//			factoryBarCodeStr.toUpperCase();
//			if(factoryBarCodeStr.length() ==24){
//				factoryBarCodeStr+='\n';
//			}
//		    if(factoryBarCodeStr.length() ==25
//		    	&&factoryBarCodeStr.charAt(24) =='\n'){
//		    	factory.setPID(factoryBarCodeStr.substring(0, 24));
//		    	initBarCode();
//		    }
                        if(factoryBarCodeStr != null){
			factoryBarCodeStr.toUpperCase();
                        factoryBarCodeStr = factoryBarCodeStr.replaceAll("\r|\n", "");
                        factoryBarCodeStr = getMacString(factoryBarCodeStr);
                        if(!factory.checkMacIsValid(factoryBarCodeStr)){
                        factoryBarCodeStr = "null";
                        }
                        } else {
                        factoryBarCodeStr = "null";
                        }
			
			if(factoryBarCodeStr.length()<=17&& !factoryBarCodeStr.equals("null")/*&&factoryBarCodeStr.charAt(factoryBarCodeStr.length()-1)=='\n'*/){
//				factory.setPID(factoryBarCodeStr.substring(0, factoryBarCodeStr.length()));
                                boolean ret = factory.setMAC(factoryBarCodeStr);
				barCodeTextViewValue.setText(factoryBarCodeStr);
                                if(ret == true){
                                barCodeTextViewPresentationText.setText("OK");
                                barCodeTextViewPresentationText.setTextColor(Color.GREEN);;
                                } else {
                                barCodeTextViewPresentationText.setText("ERROR");
                                barCodeTextViewPresentationText.setTextColor(Color.RED);;
                                }
			//	initBarCode();	
			} else {
                                barCodeTextViewPresentationText.setText("ERROR");
                                barCodeTextViewPresentationText.setTextColor(Color.RED);;
                        }
				factoryBarCodeStr ="";
//				Message message = new Message();
//                message.what = 1;
//                handler.sendMessage(message);
				
			
			
			
		}
	};
	
	 final Handler handler = new Handler(){
         @Override
         public void handleMessage(Message msg){
             super.handleMessage(msg);
             if(msg.what == 1){
            	Log.v("tv","handlemessage initbarcode");
            	initBarCode();
             }
         }
     };
     
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext=this;
		LayoutInflater vi = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mRootLayout = (RelativeLayout)vi.inflate(R.layout.factory_menu_bar_code_view,null);
		setContentView(mRootLayout);
		initView();
		mEditText =new EditText(this);
		factory=FactorySetting.getInstance(this);

                IntentFilter filter = new IntentFilter();
		filter.addAction("com.homwee.action.STOP_BARCODE_SCAN");
		stopBroadcastReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
                             finish();
			}
		};
		registerReceiver(stopBroadcastReceiver, filter);
	}
	private void initView() {

		barCodeTextViewValue = (TextView)findViewById(R.id.factory_bar_code_view_value);
		barCodeTextViewPresentationText = (TextView)findViewById(R.id.factory_bar_code_view_presentation_text);
                barCodeTextViewPresentationText.setTextColor(Color.WHITE);;
		barCodeTextViewPid = (TextView)findViewById(R.id.factory_bar_code_view_pid);
		mainLayout =(RelativeLayout)mRootLayout.findViewById(R.id.common_bar_code_view);
                barCodeTextViewPid.setText("Mac");
	    mainLayout.setBackgroundResource(R.drawable.factory_toast);
	    mainLayout.getBackground().setAlpha(200);
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
                Log.d("tv","keyCode "+keyCode);
		switch (keyCode) {
		case KeyEvent.KEYCODE_3D_MODE:
		//zcj 2018-10-31 case KeyEvent.KEYCODE_CHMIR_INPUT_SOURCE:
		case KeyEvent.KEYCODE_SETTINGS:
		case KeyEvent.KEYCODE_MENU:
			this.finish();
			Log.v("KEYCODE_MENU","KEYCODE_MENU="+KeyEvent.KEYCODE_MENU);
			return true;
		//zcj 2018-10-31 case KeyEvent.KEYCODE_CHMIR_STRIP_CODE:
		//case FactoryKeyCode.CH_FACTORY_BARCODE:
			//this.finish();
			//Intent intent = new Intent(this,BarCodeShowActivity.class);
			//startActivity(intent);
			//zcj 2018-10-31 Log.v("FACTORY_BARCODE","FACTORY_BARCODE="+KeyEvent.KEYCODE_CHMIR_STRIP_CODE);
			//zcj 2018-10-31 return true;
		default:
			mEditText.setText("");
			mEditText.onKeyDown(keyCode, event);
			factoryBarCodeStr +=mEditText.getText().toString();
			
			Log.v("tv" ,"factoryBarCodeStr1 ="+factoryBarCodeStr);
			Log.v("tv" ,"factoryBarCodeStr length ="+factoryBarCodeStr.length());
			//barCodeTextViewValue.setText(factoryBarCodeStr);
			if(barCodeTextViewPresentationText.getText().toString().equals("Processing...")){
				Log.v("tv" ,"factoryBarCodeStr2 ="+factoryBarCodeStr);
			}else{
				Log.v("tv" ,"factoryBarCodeStr3 ="+factoryBarCodeStr);
				barCodeTextViewValue.setText("");
				barCodeTextViewPresentationText.setText("Processing...");
                                barCodeTextViewPresentationText.setTextColor(Color.WHITE);;
			}
			Log.v("barcode","runtime:"+System.currentTimeMillis());
			
			
			
			   long cur =  System.currentTimeMillis();
				if(cur-startTime<500&&future!=null&&!future.isDone()){
					future.cancel(true);
				}
				
				startTime = cur;
                future = ses.schedule(mRunnable,500,TimeUnit.MILLISECONDS);
			
			
			
			
			
//			if(startTime==0){
//				startTime= System.currentTimeMillis();
//			}else{
//				
//				if(System.currentTimeMillis()-startTime >= 500){
//					mHandler.removeCallbacks(mRunnable);
//					mHandler.postDelayed(mRunnable, 500);
//					
//				}
//				
//				startTime=System.currentTimeMillis()-startTime;
//			}
//				
			
			
			break;
		}
		return super.onKeyDown(keyCode, event);

	}

protected void onStart() {
	super.onStart();
	initBarCode();
}

private void initBarCode(){
	Log.v("tv" ,"initBarCode");
/*	int pidStatus =0;
	factoryBarCodeStr =factory.getPID();
	pidStatus =factory.getPIDStatus();//0:valid  1:null  2:invlaid
	
	if(pidStatus==2) {
		if(factoryBarCodeStr.length()>=24){
			factoryBarCodeStr =  factoryBarCodeStr.substring(0,24);
		}
		//zcj 2018-10-31 barCodeTextViewValue.setTextColor(R.color.black);
		//zcj 2018-10-31 barCodeTextViewPresentationText.setTextColor(R.color.black);
		//zcj 2018-10-31barCodeTextViewPid.setTextColor(R.color.black);
	   barCodeTextViewValue.setText(factoryBarCodeStr);
	   barCodeTextViewPresentationText.setText("ERROR");

	}else if(pidStatus==0){
		if(factoryBarCodeStr.length()>=24){
			factoryBarCodeStr =  factoryBarCodeStr.substring(0,24);
		}
		//zcj 2018-10-31barCodeTextViewValue.setTextColor(R.color.black);
		//zcj 2018-10-31barCodeTextViewPid.setTextColor(R.color.black);
		//zcj 2018-10-31 barCodeTextViewPresentationText.setTextColor(R.color.black);
	   barCodeTextViewValue.setText(factoryBarCodeStr);
	   barCodeTextViewPresentationText.setText("OK");
	}else {
		//zcj 2018-10-31 barCodeTextViewValue.setTextColor(R.color.black);
		//zcj 2018-10-31 barCodeTextViewPid.setTextColor(R.color.black);
		//zcj 2018-10-31 barCodeTextViewPresentationText.setTextColor(R.color.black);
		   barCodeTextViewPresentationText.setText("NO PID");
		}
*/
        String MacAddr = factory.getMAC(); 
        if(MacAddr != null){
	   barCodeTextViewValue.setText(MacAddr);
        } else {
	   barCodeTextViewValue.setText("No Mac");
        }
	factoryBarCodeStr ="";
}

private String getMacString(String macString){
        Log.d("tv","getMacString "+ macString+" 0-4 "+macString.substring(0,4));
        if(macString.substring(0,4).equals("MAC:")){
           if(macString.substring(4).contains(":")){
           return macString.substring(4);
        } else {
           StringBuffer sb = new StringBuffer();
           for(int i = 4; i < macString.length();i = i+2){
              sb.append(macString.charAt(i));
              sb.append(macString.charAt(i+1));
              if(i+2 != macString.length()){
              sb.append(":"); 
              }
           }
        return sb.toString();
        }
        } else {
            return "null";
        }
        
}
@Override
public void onDestroy() {
	// TODO Auto-generated method stub
	if(stopBroadcastReceiver != null)
		unregisterReceiver(stopBroadcastReceiver);
	super.onDestroy();
}

}
